package de.hs_zigr.inf.iib08gruppe5powerfish.it.boundary;

import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.File;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.SwingUtilities;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.CollectionManagementService;
import org.xmldb.api.modules.XMLResource;

/**
 * To upload XML-files to an eXist data base.
 */
public class GUIUploader {

	private Database database = null;

	public void uploadXML(Collection col, File f) throws XMLDBException {
		XMLResource document = (XMLResource) col.createResource(f.getName(),
				XMLResource.RESOURCE_TYPE);
		document.setContent(f);
		col.storeResource(document);
	}

	public Collection openCollection(String dburi, String collection)
			throws XMLDBException {
		String driver = "org.exist.xmldb.DatabaseImpl";
		String dbURI = "xmldb:exist://" + dburi + "/exist/xmlrpc/db";
		Class cl;
		try {
			cl = Class.forName(driver);
			this.database = (Database) cl.newInstance();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		DatabaseManager.registerDatabase(database);
		// try to get collection
		// last params are user / password
		Collection col = DatabaseManager.getCollection(dbURI + collection,
				"admin", "aaa");
		if (col == null) {
			final JPasswordField jpf = new JPasswordField();
			JOptionPane jop = new JOptionPane(jpf,
					JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
			JDialog dialog = jop.createDialog("AdminPasswort:");
			dialog.addComponentListener(new ComponentAdapter() {
				@Override
				public void componentShown(ComponentEvent e) {
					SwingUtilities.invokeLater(new Runnable() {
						public void run() {
							jpf.requestFocusInWindow();
						}
					});
				}
			});

			dialog.setVisible(true);
			int result = (Integer) jop.getValue();
			dialog.dispose();
			char[] password = null;
			if (result == JOptionPane.OK_OPTION) {
				password = jpf.getPassword();
			}
			String passwort = new String(password);
			Collection root = DatabaseManager.getCollection(dbURI, "admin",
					passwort);
			CollectionManagementService mgtService = (CollectionManagementService) root
					.getService("CollectionManagementService", "1.0");
			col = mgtService.createCollection(collection);
		}
		return col;
	}
}